/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.skywalking.apm.plugin.lettuce.v5.memory;

import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.plugin.lettuce.v5.LettucePluginConfig;
import org.apache.skywalking.apm.plugin.lettuce.v5.RedisChannelWriterInterceptor2;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class MemoryStorage {

    private static ILog LOGGER = LogManager.getLogger(RedisChannelWriterInterceptor2.class);

    private static final MemoryStorage INSTANCE = new MemoryStorage();

    private static final Map<String, AtomicLong> HOT_KEY_MAP = new ConcurrentHashMap<>();

    private static final Map<String, Long> BIG_KEY_MAP = new ConcurrentHashMap<>();

    static {
        LOGGER.info("init MemoryStorage");
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            LOGGER.info("newSingleThreadScheduledExecutor MemoryStorage HOT_KEY_MAP={}", HOT_KEY_MAP.size());
            if (!BIG_KEY_MAP.isEmpty()) {
                BIG_KEY_MAP.entrySet();
                LOGGER.info("bigKey:{}", BIG_KEY_MAP);
                BIG_KEY_MAP.clear();
            }

            if (!HOT_KEY_MAP.isEmpty()) {
                for (Map.Entry<String, AtomicLong> m : HOT_KEY_MAP.entrySet()) {
                    if (m.getValue().longValue() < LettucePluginConfig.Plugin.Lettuce.REDIS_PARAMETER_HOT_COUNT) {
                        HOT_KEY_MAP.remove(m.getKey());
                    }
                }
                LOGGER.info("hotKey:{}", HOT_KEY_MAP);
                HOT_KEY_MAP.clear();
            }
        }, 30L, 60L, TimeUnit.SECONDS);
    }

    private MemoryStorage() {
    }

    public static final MemoryStorage getInstance() {
        return INSTANCE;
    }

    public void addHotKey(String key) {
        LOGGER.info("hotKey:{}", key);
        AtomicLong atomicLong = HOT_KEY_MAP.get(key);
        LOGGER.info("hotKey size:{}", HOT_KEY_MAP.size());
        if (atomicLong != null) {
            atomicLong.incrementAndGet();
            return;
        }
        synchronized (key.intern()) {
            atomicLong = HOT_KEY_MAP.get(key);
            if (atomicLong != null) {
                atomicLong.incrementAndGet();
                return;
            }
            HOT_KEY_MAP.put(key, new AtomicLong(1));
        }
    }

    public void addBigKey(String key, Long size) {
        if (size < LettucePluginConfig.Plugin.Lettuce.REDIS_PARAMETER_BIG_LENGTH) {
            return;
        }
        Long len = BIG_KEY_MAP.get(key);
        if (len != null && size <= len) {
            return;
        }
        BIG_KEY_MAP.put(key, size);
    }

}
